package util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;


public class EncryptUtil {
    public static String getMD5(String str) {

        try {

            // 生成一个MD5加密计算摘要

            MessageDigest md = MessageDigest.getInstance("MD5");

            // 计算md5函数

            md.update(str.getBytes());

            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符

            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值

            return new BigInteger(1, md.digest()).toString(16);

        } catch (Exception e) {

            e.printStackTrace();

            return str;

        }

    }

    //获取上月日期
    public static String getLastMonth(){
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM");
        String time = dateFormat.format(date);
        int year = Integer.parseInt(time.substring(0,4));
        int month = Integer.parseInt(time.substring(5,7));
        if(month == 1) {
            year -= 1;
            month = 12;
        }else {
            month -=1;
        }
        if(month <10)
            time = year + "-0" + month;
        else
            time = year + "-" + month;
        return time;
    }

    public static void main(String[] args) {
        System.out.println(EncryptUtil.getMD5("123456"));
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM");
        String time = dateFormat.format(date);
        int moth = Integer.parseInt(time.substring(0,4));
        System.out.println(moth);
        System.out.println(getLastMonth());
    }

}